/*
 * Copyright 2008 Karel Klic.
 * This file is part of Oslavanský Bot.
 * 
 * Oslavanský Bot is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.

 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package categorybot;

import java.util.regex.*;
import org.apache.commons.lang.StringUtils;

public class CategoryRemover {

  /**
   * Removes a category from word definition text.
   * @param text
   * Word definition text.
   * @param categoryId
   * Category name without the category prefix and without brackets.
   * @return
   * Word definition text without the category.
   */
  public static String removeCategory(String text, String categoryId) {

    Pattern pattern = PatternFactory.getCategoryPattern(categoryId);
    assert pattern.matcher(text).find();

    Matcher matcher = pattern.matcher(text);
    if (!matcher.find()) {
      return text;    // create result buffer.
    }
    StringBuffer buffer = new StringBuffer();
    buffer.append(text.substring(0, matcher.start()));
    String remainder = StringUtils.stripStart(text.substring(matcher.end()), " \n\r\t");
    buffer.append(remainder);

    // zjistime, zda je pred nami kategorie.
    int position = matcher.start();
    boolean categoryBefore = false;
    Pattern categoryPatternBefore = Pattern.compile("\\[\\[\\s*Kategorie:[ \t]*\\p{L}[\\p{L}\t ]*\\s*\\]\\]\\s*", Pattern.MULTILINE);
    Matcher categoryMatcherBefore = categoryPatternBefore.matcher(buffer.toString());
    while (categoryMatcherBefore.find()) {
      if (categoryMatcherBefore.start() <= position &&
              categoryMatcherBefore.end() >= position) {
        categoryBefore = true;
        break;
      }
    }

    // zjistime, zda je za nami kategorie.
    boolean categoryAfter = false;
    Pattern categoryPatternAfter = Pattern.compile("\\s*\\[\\[\\s*Kategorie:[ \t]*\\p{L}[\\p{L}\t ]*\\s*\\]\\]", Pattern.MULTILINE);
    Matcher categoryMatcherAfter = categoryPatternAfter.matcher(buffer.toString());
    categoryAfter = position < buffer.toString().length() &&
            categoryMatcherAfter.find(position) &&
            categoryMatcherAfter.start() == position;

    // pokud je pred nami kategorie a za nami neni, vlozime odradkovani navic.
    if (categoryBefore && !categoryAfter) {
      buffer.insert(position, '\n');
    }
    return buffer.toString();
  }
}
